package com.djinfo.work.controller;

import com.djinfo.work.common.bean.AjaxJson;
import com.djinfo.work.entity.SysNewsEntity;
import com.djinfo.work.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * Created by gz on 2017/5/10.
 */
@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @ResponseBody
    @RequestMapping("/save.do")
    public AjaxJson saveNews(SysNewsEntity news, HttpServletRequest request){
        String id = String.valueOf(request.getSession().getAttribute("userId"));
        AjaxJson ajaxJson = new AjaxJson();
        try{
            newsService.saveNews(news,id+"");
            ajaxJson.setCode(101);
            ajaxJson.setMsg("success");
        }catch (Exception e){
            ajaxJson.setCode(201);
            ajaxJson.setMsg("error");
            e.printStackTrace();
        }
        return ajaxJson;
    }

    /**
     * 列表
     */
    @RequestMapping("/list.do")
    @ResponseBody
    public AjaxJson list(SysNewsEntity news, Integer pagenum, Integer pagesize){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            HashMap<String, Object> map = newsService.getPage(news,pagenum,pagesize);
            ajaxJson.setCode(101);
            ajaxJson.setMsg("success");
            ajaxJson.setResult(map);
        }catch (Exception e){
            ajaxJson.setCode(201);
            ajaxJson.setMsg("error");
        }
        return ajaxJson;
    }

    /**
     * 获取对象信息
     */
    @RequestMapping("/info.do")
    public ModelAndView info(SysNewsEntity news){
        AjaxJson ajaxJson = new AjaxJson();
        HashMap<String, Object> map = new HashMap<>();
        try{

            SysNewsEntity res = newsService.selectOne(news);
            map.put("data",res);
            ajaxJson.setCode(101);
            ajaxJson.setMsg("success");
            ajaxJson.setResult(map);
        }catch (Exception e){
            ajaxJson.setCode(201);
            ajaxJson.setMsg("error");
        }

        return new ModelAndView("news/edit.html","map",map);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public AjaxJson delete(SysNewsEntity news){
        AjaxJson ajaxJson = new AjaxJson();
        try{
            newsService.delete(news);
            ajaxJson.setCode(101);
            ajaxJson.setMsg("success");
        }catch (Exception e){
            ajaxJson.setCode(201);
            ajaxJson.setMsg("error");
        }
        return ajaxJson;
    }


}
